<template>
  <div>
    <device-login-card @logined="handleToken" />
    <el-form inline>
      <el-form-item label="卡号">
        <el-input v-model="form.card" />
        <!-- <el-input v-model="form.card" @change="getOccupations" /> -->
      </el-form-item>

      <el-form-item>
        <el-button type="text" icon="el-icon-refresh" @click="getOccupations" />
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item>
        <el-button @click="handleStoreIn">存储</el-button>
        <el-button v-for="(v,i) in permissions" :key="'store_'+i" @click="handleTakeOut(v)">{{v.deviceIndex}} : 取物
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import DeviceLoginCard from './common/DeviceLoginCard.vue';
  import request from "@/utils/request";
  export default {
    name: 'LockerTester',
    components: {
      DeviceLoginCard
    },
    data() {
      return {
        form: {
          card: 'Card00001'
        },
        token: {
          userToken: null,
          sessionToken: null,
        },
        device: {
          id: null
        },
        permissions: []
      }
    },
    methods: {
      handleToken(data) {
        this.device = Object.assign({}, data.device)
        this.token = Object.assign({}, data)
        this.getOccupations()
      },
      getOccupations() {
        const vm = this
        request({
          method: 'get',
          url: `/device/locker/occupations/${this.device.id}/${this.form.card}`,
        }).then(res => {
          vm.permissions = [].concat(res.data.permissions)
        })
      },
      handleStoreIn() {
        const vm = this
        request({
          method: 'get',
          url: `/device/locker/store/${this.device.id}/${this.form.card}`
        }).then(res => {
          vm.permissions.push(res.data)
        })
      },
      handleTakeOut(permission) {
        const vm = this
        request({
          method: 'get',
          url: `/device/locker/take/${permission.deviceId}/${permission.deviceIndex}/${this.form.card}`
        }).then(() => {
          for (var i = 0; i < this.permissions.length; i++) {
            const each = this.permissions[i]
            if (permission.deviceId === each.deviceId && permission.deviceIndex === each.deviceIndex) {
              this.permissions.splice(i, 1)
              break
            }
          }
        })
      }
    }
  }

</script>
